import React, { Component } from 'react';
import { Button, Form, Input, Radio, Space, Select, Cascader } from "antd";
import { CloseCircleOutlined, PlusOutlined } from '@ant-design/icons';
import {apiGetGoodsClassifyTree} from '@/request/mallManagement'
import {apiActivityLinkList} from "@/request/h5"
import TheUpload from "@/components/TheUpload";
const { Option } = Select
const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
    },
};
const formItemLayoutWithOutLabel = {
    wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 20, offset: 4 },
    },
};
class Editor extends Component {
    constructor(props) {
        super(props)
        this.state = {
            fileList: null,
            radioValue: '',
            visible: false,
            configCarouselUri: '',
            category: '',
            configCarouselSite: "",
            arr: [],
            activeList: [],
            newMemberValue: '0',
            initialValues: {
                configCarouselType: '',
                newMemberShow: '0',
            },
            options:[],
        }
    }

    componentDidMount() {
        this.getActiveList()
        if (this.props.configCarouselSite) {
            this.setState({ configCarouselSite: this.props.configCarouselSite })
        } else {
            this.setState({ configCarouselSite: "" })
        };
        if (this.props.category === "button") {
            this.setState({

            })
        }
        if (this.props.type === 'editor') {
            console.log(this.props.data);
            let value = { ...this.props.data }
            if (value.configCarouselType === '1') {
                let users = []
                let url = []
                if (value.configCarouselUri.indexOf('?') != '-1') {
                    url = value.configCarouselUri.split('?')
                    value.configCarouselUri = url[0]
                    users = url[1].split('&')
                    let str = ''
                    users.map((item) => {
                        str = item.split('=')
                        this.state.arr.push({
                            key: str[0],
                            value: str[1]
                        })
                    })
                } else {
                    value.configCarouselUri = value.configCarouselUri.trim()
                }
            }else{
                value.configCarouselUri = JSON.parse(value.configCarouselUri)
            }
            this.formRef.setFieldsValue({ ...value })
            const fileList = [
                {
                    uid: '-1',
                    name: 'image.png',
                    status: 'done',
                    url: value.configCarouselFilez,
                },
            ]
            this.setState({
                fileList,
                radioValue: value.configCarouselType,
                btnLoading: value.btnLoading,
                dialogCancel: value.dialogCancel,
            }, () => {
                console.log(this.state, 'ssss')
            })
        }
        this.getClassifyTree()
    }
    getClassifyTree = async () =>{
        let res = await apiGetGoodsClassifyTree() 
        this.setState({
            options:res.data
        })
    }
    /**
     * @desc 设置新闻内容表单默认值
     * */
    // setNewsContent = (data) => {
    //     this.setState({
    //         configCarouselContent: data
    //     })
    //     this.formRef.setFieldsValue({ configCarouselContent: data })
    // }
    /**
     * @desc 获取图片Id插入到form表单中
     * @param data
     */
    getFileResult = data => {
        if (data && data.length > 0) {
            let str = data.map(v => {
                if (v.response && v.response.code === 0) {
                    return v.response.data
                } else {
                    return ''
                }
            }).join(',')
            this.formRef.setFieldsValue({ configCarouselFilez: str })
        } else {
            this.formRef.setFieldsValue({ configCarouselFilez: '' })
        }
    }
    radioChange = (e) => {
        this.setState({
            configCarouselUri: ''
        }, () => {
            this.formRef.setFieldsValue({ configCarouselUri: '', users: '' })
            const CarouselType = e.target.value
            if (CarouselType === '1') {
                this.setState({
                    configCarouselUri: '',
                    users: ''
                })
            }
            this.setState({
                radioValue: e.target.value,
            })
        })
    }
    // 外链地址下拉内容
    async getActiveList() {
        await apiActivityLinkList().then(res => {
            console.log(res);
            if (res.code === 0) {
                this.setState({
                    activeList: res.data
                })
            }
        })
    }
    onCancel = () => {
        this.setState({
            visible: false
        })
    }
    onOk = (e) => {

        this.setState({
            visible: false
        })
    }
    onFinish = () => {
        let value = this.formRef.getFieldValue()
        if (this.state.radioValue !== '1') {
            value.configCarouselUri = JSON.stringify(value.configCarouselUri)
        } else {
            value.configCarouselUri = value.configCarouselUri.trim()
        }
        let str = ''
        if (value.users && value.users.length !== 0) {
            value.users.map((item, index) => {
                str += item.key + '=' + item.value
                if (index + 1 !== value.users.length) {
                    str += '&'
                }
            })
            value.configCarouselUri = value.configCarouselUri.trim() + '?' + str
            delete value.users
        } else {
            value.configCarouselUri = value.configCarouselUri.trim()
        }
        this.props.onFinish(value)
    }
    configCarouselUriChange = (e) => {
        this.formRef.setFieldsValue({ users: '' })
        this.setState({
            configCarouselUri: e
        })
    }
    newMemberChange = (e) => {
        this.formRef.setFieldsValue({ newMemberShow: e.target.value })
        this.setState({
            newMemberValue: e.target.value,
        })
    }
    cascaderChange = async (value) => {
        // this.formRef.setFieldsValue({configCarouselUri:JSON.stringify(value)})
        this.setState({
            initialValues:{
                configCarouselUri:value
            },
            cascader:value
        })
    }
    render() {
        const { btnLoading, radioValue, configCarouselUri,initialValues, arr, activeList,newMemberValue,options,cascader} = this.state
        const { data, dialogCancel } = this.props
        return (
            <Form
                ref={(ref) => {
                    this.formRef = ref;
                }}
                {...formItemLayout}
                onFinish={this.onFinish}
                initialValues={
                    initialValues
                }
            >
                <Form.Item rules={[{ required: true, message: '请输入标题' }]} name={'configCarouselTitle'} label={'标题'}>
                    <Input maxLength={20} />
                </Form.Item>
                <Form.Item rules={[{ required: true, message: '请选择图片' }]} name={'configCarouselFilez'} label={'图片'}>
                    {this.props.data && this.state.fileList && this.state.fileList.length &&
                        <TheUpload isConversion={false} maxSize={10} fileList={this.state.fileList} data={{ attachKey: '1' }} len={1}
                            getFileResult={this.getFileResult} />}
                    {
                        !this.props.data && <TheUpload isConversion={false} maxSize={10} data={{ attachKey: '1' }} len={1}
                            getFileResult={this.getFileResult} />
                    }
                </Form.Item>
                <Form.Item rules={[{ required: true, message: '请选择' }]} name={'newMemberShow'} label={'是否只对新人展示'} >
                    <Radio.Group defaultValue={newMemberValue} >
                        <Radio onClick={(e) => this.newMemberChange(e)} value={'1'}>是</Radio>
                        <Radio onClick={(e) => this.newMemberChange(e)} value={'0'}>否</Radio>
                    </Radio.Group>
                </Form.Item>
                <Form.Item rules={[{ required: true, message: '请输入位置排序' }, { pattern: /^[0-9]*$/, message: '只能输入数字' }]} name={'configCarouselSort'} label={'位置排序'}>
                    <Input maxLength={5} placeholder="*App展示顺序由小到大,相同排序按添加先后顺序展示" />
                </Form.Item>
                <Form.Item rules={[{ required: true, message: '请选择外链' }]} name={'configCarouselType'} label={'外链'}>
                    <Radio.Group onChange={this.radioChange} initialValue={radioValue} buttonStyle="solid" optionType='button' >
                        <Radio onClick={this.radioChange} value={'1'}>地址链接</Radio>
                        <Radio onClick={this.radioChange} value={'18'}>商品类目</Radio>
                        <Radio onClick={this.radioChange} value={'17'}>全部分类</Radio>
                    </Radio.Group>
                </Form.Item>
                <Form.Item name={'configCarouselUri'}
                    label={radioValue === '1'?'选择链接':'商品类目'}
                    rules={[{ required: radioValue === '17' ? false : true, message: '请选择链接' }]}>
                    {radioValue === '1' ? <Select onChange={this.configCarouselUriChange}>
                        {
                            activeList.map(item => <Option value={item.activityLink} key={item.id}>{item.activityName}</Option>)
                        }
                    </Select> : radioValue === '18' ?
                    <Cascader  options={options} defaultValue={cascader} width={200} onChange={(e)=>{this.cascaderChange(e)}} changeOnSelect placeholder="请选择商品类目" />        
                    : <Input readOnly placeholder="无需填写" />
                }
                </Form.Item>
                {radioValue === '1' && configCarouselUri !== '' ? <Form.List name="users" initialValue={arr}>
                        {(fields, { add, remove }) => (
                            <>
                                <Form.Item label="参数">
                                    <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                                        添加参数
                                    </Button>
                                </Form.Item>
                                {fields.map(({ key, name, ...restField }) => (
                                    <Form.Item
                                        {...formItemLayoutWithOutLabel}
                                        required={false}
                                        key={key}
                                        style={{
                                            margin: 0
                                        }}
                                    >
                                        <Space
                                            style={{
                                                display: 'flex',
                                                marginBottom: 0,
                                            }}
                                            align="baseline"
                                        >
                                            <Form.Item
                                                {...restField}
                                                name={[name, 'key']}
                                                rules={[
                                                    {
                                                        required: true,
                                                        message: '请输入参数名',
                                                    },
                                                ]}

                                            >
                                                <Input placeholder="参数名" />
                                            </Form.Item>
                                            <Form.Item
                                                {...restField}
                                                name={[name, 'value']}
                                                rules={[
                                                    {
                                                        required: true,
                                                        message: '请输入参数值',
                                                    },
                                                ]}
                                            >
                                                <Input placeholder="参数值" />
                                            </Form.Item>
                                            <CloseCircleOutlined onClick={() => remove(name)} />
                                        </Space>
                                    </Form.Item>
                                ))}
                            </>
                        )}
                    </Form.List> : null
                }
                <div className="p-text-align">
                    <Space size="large">
                        <Button key="back" onClick={dialogCancel}>
                            取 消
                        </Button>
                        <Button type="primary" loading={btnLoading} htmlType="primary">
                            确 定
                        </Button>
                    </Space>
                </div>
            </Form>
        );
    }
}

export default Editor;
